package com.ruoyi.oauth.wx.service.Impl;

import com.ruoyi.common.utils.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson2.JSONObject;
import com.ruoyi.auth.common.domain.OauthUser;
import com.ruoyi.auth.common.service.IOauthUserService;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.framework.web.service.TokenService;
import com.ruoyi.framework.web.service.UserDetailsServiceImpl;
import com.ruoyi.oauth.wx.constant.WxMiniAppConstant;
import com.ruoyi.oauth.wx.service.WxLoginService;
import com.ruoyi.system.service.ISysUserService;
import org.springframework.util.ObjectUtils;

import java.util.Random;

@Service
public class WxMiniAppLoginServiceImpl implements WxLoginService {
    @Autowired
    private WxMiniAppConstant wxAppConstant;

    @Autowired
    private TokenService tokenService;

    @Autowired
    private UserDetailsServiceImpl userDetailsServiceImpl;

    @Autowired
    private ISysUserService userService;

    @Autowired
    private IOauthUserService oauthUserService;

    @Override
    public String doLogin(String code) {
        JSONObject doAuth = doAuth(
                wxAppConstant.getUrl(),
                wxAppConstant.getAppId(),
                wxAppConstant.getAppSecret(),
                code);
        String openid = doAuth.getString("openid");
        OauthUser selectOauthUser = oauthUserService.selectOauthUserByUUID(openid);
        SysUser sysUser = userService.selectUserByOpenId(openid);
        if (sysUser == null){
            sysUser = new SysUser();
            sysUser.setUserName(openid);
            sysUser.setNickName(openid);
            sysUser.setOpenId(openid);
            // 随机生成密码
            String password = String.valueOf(new Random().nextInt(999999));
            sysUser.setPassword(SecurityUtils.encryptPassword(password));
            userService.registerUser(sysUser);
        }
        //这里没有数据则自动新增用户
        if (selectOauthUser == null) {
            selectOauthUser = new OauthUser();
            selectOauthUser.setUserId(sysUser.getUserId());
            selectOauthUser.setOpenId(doAuth.getString("openid"));
            selectOauthUser.setUuid(doAuth.getString("openid"));
            selectOauthUser.setSource("WXMiniApp");
            selectOauthUser.setAccessToken(doAuth.getString("session_key"));
            oauthUserService.insertOauthUser(selectOauthUser);
        }else if (!ObjectUtils.isEmpty(selectOauthUser.getUserId())
        && !selectOauthUser.getUserId().toString().equals(sysUser.getUserId().toString())){
            selectOauthUser.setUserId(sysUser.getUserId());
            oauthUserService.updateOauthUser(selectOauthUser);
        }
        LoginUser loginUser = (LoginUser) userDetailsServiceImpl.createLoginUser(sysUser);
        loginUser.setOpenId(openid);
        return tokenService.createToken(loginUser);
    }



    @Override
    public String doRegister(OauthUser oauthUser) {
        if (StringUtils.isEmpty(oauthUser.getCode())) {
            return "没有凭证";
        }
        if (oauthUser.getUserId() == null) {
            return "请先注册账号";
        }
        if (oauthUserService.checkAuthUser(oauthUser.getUserId(), "WXMiniApp")) {
            return "该用户已绑定微信";
        }
        JSONObject doAuth = doAuth(
                wxAppConstant.getUrl(),
                wxAppConstant.getAppId(),
                wxAppConstant.getAppSecret(),
                oauthUser.getCode());
        oauthUser.setOpenId(doAuth.getString("openid"));
        OauthUser ou = oauthUserService.selectOauthUserByOpenId(oauthUser.getOpenId());
        if (ou != null && ou.getUserId() != null && oauthUser.getUserId() != null
                && !ou.getUserId().toString().equals(oauthUser.getUserId().toString())){
            ou.setUserId(oauthUser.getUserId());
            oauthUserService.updateOauthUser(ou);
            return "";
        }
        oauthUser.setUuid(doAuth.getString("openid"));
        oauthUser.setSource("WXMiniApp");
        oauthUser.setAccessToken(doAuth.getString("session_key"));
        oauthUserService.insertOauthUser(oauthUser);
        return "";
    }

}
